package MyGO.controller;

import MyGO.Form.TrackForm;
import MyGO.entity.Doctor;
import MyGO.service.IDoctorService;
import MyGO.service.ITrackFormService;
import MyGO.service.impl.DoctorServiceImpl;
import MyGO.service.impl.TrackFormServiceImpl;
import MyGO.utils.RegexUtila.RegexUtils;
import MyGO.utils.enumerastion.Department;
import MyGO.utils.enumerastion.DoctorLevel;
import MyGO.utils.enumerastion.VisTiOnDay;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.control.*;
import javafx.util.StringConverter;

import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class GuaHao {

    @FXML
    private TextField binglihao;

    @FXML
    private DatePicker chushengriqi;

    @FXML
    private ChoiceBox<String> guahaokeshi;

    @FXML
    private TextField jiatingzhuzhi;

    @FXML
    private ChoiceBox<String> jiesuanleibie;

    @FXML
    private DatePicker kanzhenriqi;

    @FXML
    private ChoiceBox<Doctor> kanzhenyisheng;

    @FXML
    private TextField money;

    @FXML
    private TextField nianling;

    @FXML
    private ChoiceBox<String> nianlingxuanze;

    @FXML
    private TextField shenfenzheng;

    @FXML
    private TextArea shengyvhaoe;

    @FXML
    private ChoiceBox<String> shoufeifangshi;

    @FXML
    private Button sure;

    @FXML
    private Button unsure;
    @FXML
    private ChoiceBox<String> haobie;

    @FXML
    private ChoiceBox<String> wubie;

    @FXML
    private ChoiceBox<String> xingbie;

    @FXML
    private TextField xingming;

    @FXML
    private TextArea zonghaoe;
    private Integer years;
    private Integer months;
    private Integer days;
    private LocalDate selectedDate;
    private LocalDate currentDate;
    private IDoctorService temp = new DoctorServiceImpl();
    private TrackForm input = new TrackForm();

    private ITrackFormService trackFormService = new TrackFormServiceImpl();;

    public void initialize() {
        //初始化可选数据

        wubie.getItems().addAll("早上","下午","全天");
        xingbie.getItems().addAll("男性","女性","双性","沃尔玛购物袋","武装直升机","其他");
        nianlingxuanze.getItems().addAll("年","月","日");
        shoufeifangshi.getItems().addAll( "就诊卡");
        shoufeifangshi.setValue("就诊卡");
        jiesuanleibie.getItems().addAll("就诊卡");
        jiesuanleibie.setValue("就诊卡");
        guahaokeshi.getItems().addAll("内科","外科","儿科");
        haobie.getItems().addAll("普通医生", "专家","教授");
        haobie.setValue("普通医生");
        //设置填入的数据

        //检查身份证号，并自动选择生日
        shenfenzheng.focusedProperty().addListener((observable, oldValue, newValue) -> {
            if (!newValue){
                //识别身份证号是否正确
                if (!RegexUtils.isMatch(shenfenzheng.getText(), "^[1-9]\\d{5}(18|19|20)\\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\\d|3[01])\\d{3}([0-9]|X)$")){
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("身份证号格式错误!");
                    shenfenzheng.clear();
                    alert.showAndWait();
                }else {
                    //自动填充生日
                    // 提取身份证中的出生日期部分
                    String birthDateStr = shenfenzheng.getText(6, 14);
                    // 格式化日期
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                    LocalDate birthDate = LocalDate.parse(birthDateStr, formatter);
                    // 更新DatePicker的值
                    chushengriqi.setValue(birthDate);
                }
            }
        });
        //病历号
        binglihao.setText(input.getId());
        binglihao.setEditable(false);
        //默认当日看诊
        kanzhenriqi.setValue(LocalDate.now());
        kanzhenriqi.setEditable(false);
        kanzhenriqi.setDisable(true);
        //得到年龄
        chushengriqi.setOnAction(event -> {
            if (chushengriqi.getValue() != null)
                selectedDate = chushengriqi.getValue();
            currentDate = LocalDate.now();
            years = Period.between(selectedDate, currentDate).getYears();
            months = Period.between(selectedDate, currentDate).getMonths();
            days = Period.between(selectedDate, currentDate).getDays();
        });
        //自动判断年龄
        nianlingxuanze.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            if (Objects.equals(newValue, "年")){
                nianling.setText(String.valueOf(years));
            }else if (Objects.equals(newValue, "月")){
                nianling.setText(String.valueOf(months));
            }else if (Objects.equals(newValue, "日")){
                nianling.setText(String.valueOf(days));
            }
        });
        nianling.setEditable(false);
        //根据所选科室，号别，上下午判断可选医生
        kanzhenyisheng.showingProperty().addListener((obs,wasShowing,isShowing) ->{
            if (isShowing) {
                List<Doctor> filteredPeople = temp.selevtAllDoctor().stream()
                        .filter(docter -> {
                            boolean pass = true;
                            if (guahaokeshi.getValue() != null) {
                                pass = pass && docter.getDepartment().toString().equals(guahaokeshi.getValue());
                            }
                            if (wubie.getValue() != null) {
                                pass = pass && docter.getVisTiOnDay().toString().equals(wubie.getValue());
                            }
                            if (haobie.getValue() != null) {
                                pass = pass && docter.getDoctorLevel().toString().equals(haobie.getValue());
                            }
                            return pass;
                        })
                        .collect(Collectors.toList());
                ObservableList<Doctor> observableList = FXCollections.observableArrayList(filteredPeople);
                kanzhenyisheng.setItems(observableList);
                kanzhenyisheng.setConverter(new StringConverter<Doctor>() {
                    @Override
                    public String toString(Doctor doctor) {
                        if (doctor == null)
                            return null;
                        else
                            return doctor.getName();
                    }

                    @Override
                    public Doctor fromString(String s) {
                        return null;
                    }
                });
            }

            //号额
            if (kanzhenyisheng.getValue() != null){
                //号额不足
                if (kanzhenyisheng.getValue().getUsedAmount() >= kanzhenyisheng.getValue().getInitAmount()){
                    Alert alert = new Alert(Alert.AlertType.ERROR);
                    alert.setHeaderText("号额不足!请更改医生");
                    kanzhenyisheng.getSelectionModel().select(-1);
                    alert.showAndWait();
                }else {
                    zonghaoe.setText(String.valueOf(kanzhenyisheng.getValue().getInitAmount()));
                    zonghaoe.setDisable(true);
                    shengyvhaoe.setText(String.valueOf(kanzhenyisheng.getValue().getInitAmount() - kanzhenyisheng.getValue().getUsedAmount()));
                    shengyvhaoe.setDisable(true);
                }
            }else{
                zonghaoe.setText(String.valueOf(0));
                zonghaoe.setDisable(true);
                shengyvhaoe.setText(String.valueOf(0));
                shengyvhaoe.setDisable(true);
            }
            //应收金额
            if (kanzhenyisheng.getValue() != null)
                money.setText(String.valueOf(kanzhenyisheng.getValue().getRegistFee()));
            else
                money.setText("0.00");
            money.setDisable(true);
        });

        //保存数据
        sure.setOnAction(e -> {
            //判断是否有信息未填充
            if ((xingming.getText().isEmpty() || shenfenzheng.getText().isEmpty()|| kanzhenyisheng.getValue() == null)){
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setHeaderText("请检查信息是否填写完整!");
                alert.showAndWait();
            }else{
                action();
                input = new TrackForm();
                binglihao.setText(input.getId());
                unaction();
                Alert alert = new Alert(Alert.AlertType.INFORMATION);
                alert.setHeaderText("挂号成功!");
                alert.showAndWait();
            }

        });
        //清空数据
        unsure.setOnAction(e ->{
            unaction();
        });
    }

    private void action(){

        //病人信息
        input.getPatientInfoForm().setName(xingming.getText());
        input.getPatientInfoForm().setYear(years);
        input.getPatientInfoForm().setDay(days);
        input.getPatientInfoForm().setMonth(months);
        input.getPatientInfoForm().setBirthDay(String.valueOf(selectedDate));
        input.getPatientInfoForm().setIdNum(shenfenzheng.getText());
        input.getPatientInfoForm().setAddress(jiatingzhuzhi.getText());
        input.getPatientInfoForm().setGender(xingbie.getValue());
        //挂号信息
        input.getRegistForm().setVisTiOnDay(VisTiOnDay.parseVisitTimeOnDay(wubie.getValue()));
        input.getRegistForm().setDepartment(Department.parseDepartmentType(guahaokeshi.getValue()));
        input.getRegistForm().setDoctorLevel(DoctorLevel.parseDoctorLevel(haobie.getValue()));
        input.getRegistForm().setDoctorID(kanzhenyisheng.getValue().getId());
        input.getRegistForm().setFee(kanzhenyisheng.getValue().getRegistFee());
        //减少号额
        kanzhenyisheng.getValue().addUsedAmount();
        //保存数据
        trackFormService.addTrackForm(input);
        input.setStatus_main("未叫号");
    }
    private void unaction(){
        xingming.clear();
        nianling.clear();
        shenfenzheng.clear();
        jiatingzhuzhi.clear();
        zonghaoe.clear();
        shengyvhaoe.clear();
        money.clear();
        nianlingxuanze.getSelectionModel().select(-1);
        haobie.getSelectionModel().select("普通医生");
        xingbie.getSelectionModel().select(-1);
        wubie.getSelectionModel().select(-1);
        guahaokeshi.getSelectionModel().select(-1);
        kanzhenyisheng.getItems().clear();
        kanzhenyisheng.getSelectionModel().select(-1);
        chushengriqi.setValue(null);
    }
}
